import time
import models
import cache
import json
from datetime import datetime

""" def timer(func):
    def warpper(*args,**kwargs):
        start = time.time
        res = func(*args,**kwargs)
        end = time.time
        print(end-start)
        return res
    return warpper """


def handler_index():
    """
    以二进制方式返回首页文件的内容， 并替换文件中的变量
    """
    dt = time.strftime(r"%Y%-m-%d %H:%M:%S")
    with open('templates/index.html', 'r', encoding='utf-8') as f:
        content = f.read()
        content = content.replace("{{now_dt}}", dt)
    return bytes(content, encoding='utf-8')


def handler_css():
    with open('ccs/bootstrap/css/bootstrap.css', 'r', encoding="utf-8") as f:
        content = f.read()
    return bytes(content, encoding='utf-8')

def handler_js():
    with open('js/Popup_window.js', 'r', encoding="utf-8") as f:
        content = f.read()
    return bytes(content, encoding='utf-8')

def server_data(sqldata):
    query_sql = sqldata
    conn, cursor = models.mysql_conn()
    data = models.mysql_query(cursor, query_sql)
    models.mysql_close(cursor, conn)
    return data



def server_list():
    tr_tpl = """
    <tr>
        <th>{id}</th>
        <th>{host_name}</th>
        <th>{os}</th>
    </tr>"""

    file = 'templates/server_list.html'
    st = time.time()
    data = server_data("select id,host_name,os from base_info;")
    endt = time.time()
    use_dt = endt - st

    tr = ''
    for row in data:
        tr += tr_tpl.format(**row)

    with open(file, 'r', encoding="utf-8") as f:
        content = f.read()
        content = content.replace("{{table_tr}}", tr)
        content = content.replace("{{cache}}", "未用缓存")
        content = content.replace("{{dt}}", "不用计时"+str(use_dt))

    return bytes(content, encoding='utf-8')


def mysql_or_cache():
    st = time.time()
    rs = cache.rs
    ex = rs.ttl("server_info")
    if ex >= -1:
        data = rs.get("server_info")
        data = json.loads(data)
        print(data)
    else:
        data = server_data("select id,host_name,os from base_info;")
        # 添加到缓存
        rs.set("server_info", json.dumps(data))
    endt = time.time()
    use_dt = endt - st
    tr_tpl = """
    <tr>
        <th>{id}</th>
        <th>{host_name}</th>
        <th>{os}</th>
    </tr>"""

    file = 'templates/server_list.html'

    tr = ''
    for row in data:
        tr += tr_tpl.format(**row)

    with open(file, 'r', encoding="utf-8") as f:
        content = f.read()
        content = content.replace("{{table_tr}}", tr)
        content = content.replace("{{cache}}", "使用缓存")
        content = content.replace("{{dt}}", str(use_dt))

    return bytes(content, encoding='utf-8')

def mysql_api():
    data = server_data("select id,host_name,os from base_info;")
    return bytes(json.dumps(data, indent=4), encoding='utf-8')


def mysql_api_v1_host():
    data = server_data("select ip,port from host_port;")
    return bytes(json.dumps(data, indent=4), encoding='utf-8')
